from base.web import SHandler, BaseHandler, get_files, UserHandler
import hashlib
from api.product import domin

'''
    1. 
'''

class set_config(SHandler):
    def post(self):
        config_list = ['name', 'address']
        params = []
        has_config_list = []
        for key in config_list:
            if self.get_argument(key, False):
                params.append(key + '=' + '\'' + self.get_argument(key, '') + '\'')
        if self.modify_sql('update hs_config set {params}'.format(params = ','.join(params))):
            res = self.res_success('modify')
        else:
            res = self.res_error('modify')
        self.write(res)

class modify_pwd(SHandler):
    def post(self):
        h = hashlib.sha256()
        h.update(bytes(self.get_argument('oldpwd', ''), encoding='utf-8'))
        oldpwd = h.hexdigest()
        h = hashlib.sha256()
        h.update(bytes(self.get_argument('newpwd', ''), encoding='utf-8'))
        newpwd = '\'' + h.hexdigest() + '\''
        config = self.query_sql('select adpwd from hs_config where id = 1')[0]
        print(oldpwd)
        print(newpwd)
        if config['adpwd'] == oldpwd:
            if self.modify_sql('update hs_config set adpwd = {0} where id = 1'.format(newpwd)):
                res = self.res_success('modify')
            else:
                res = self.res_error('modify')
        else:
            res = dict(
                code = 1,
                message = '旧密码错误'
            )
        self.write(res)

class config_detail(SHandler):
    def post(self):
        query_list = ['address','name']
        config = self.query_sql('select count(*) as has, {keys} from hs_config where id = 1;'.format(keys = ','.join(query_list)))[0]
        if config['has']:
            res = self.res_success('query', object=config)
        else:
            object = {}
            for key in query_list:
                object[key] = ''
            res = self.res_success('query', object=object)
        self.write(res)

class create_content(SHandler):
    def post(self):
        create_list = ['name', 'remark']
        params = []
        for key in create_list:
            params.append('\'' + self.get_argument(key, '') + '\'')
        condition = dict(
            keys = ','.join(create_list),
            values = ','.join(params)
        )
        if self.insert_sql(['insert into hs_content ({keys}) values ({values});'.format(**condition)]):
            res = self.res_success('insert')
        else:
            res = self.res_error('insert')
        self.write(res)

class query_content(UserHandler):
    def post(self):
        try:
            data = self.query_sql('select * from hs_content order by isdel')
            res = self.res_success('query', data, {'domin': domin})
        except:
            res = self.res_error('query')
        self.write(res)
    
class content_detail(SHandler):
    def post(self):
        ids = int(self.get_argument('id', ''))
        try:
            content = self.query_sql('select * from hs_content where id = {0}'.format(ids))
            res = self.res_success('query', object={'content': content[0], 'domin': domin})
        except:
            res = self.res_error('query')
        self.write(res)

class del_content(SHandler):
    def post(self):
        condition = [
            self.get_argument('isdel', 0),
            self.get_argument('id', 0)
        ]
        sql_arr = [
            'update hs_content set isdel = {0} where id = {1}'.format(*condition),
            'update hs_product set isdel = {0} where contentid = {1}'.format(*condition)
        ]
        if self.modify_sql(sql_arr):
            res = self.res_success('modify')
        else:
            res = self.res_error('modify')
        self.write(res)

class modify_content(SHandler):
    def post(self):
        modify_list = ['name', 'remark']
        params = []
        for key in modify_list:
            value = self.get_argument(key, '')
            if value:
                params.append(key + '=' + '\'' + value + '\'')
        condition = [
            ','.join(params),
            self.get_argument('id')
        ]
        if self.modify_sql('update hs_content set {0} where id = {1}'.format(*condition)):
            res = self.res_success('modify')
        else:
            res = self.res_error('modify')
        self.write(res)

class query_level(SHandler):
    def post(self):
        try:
            data = self.query_sql('select * from hs_level order by -id')
            res = self.res_success('query', data, {'domin': domin})
        except:
            res = self.res_error('query')
        self.write(res)

class islogin(SHandler):
    def post(self):
        self.write(
            dict(
                code = 0,
                message = '已登陆'
            )
        )

config_url = [
    #修改配置
    (r"/api/config/set_config", set_config),
    #配置详情
    (r"/api/config/config_detail", config_detail),
    #添加业务
    (r"/api/config/create_content", create_content),
    #查询业务
    (r"/api/config/query_content", query_content),
    #业务详情  
    (r"/api/config/content_detail", content_detail),
    #业务删除
    (r"/api/config/del_content", del_content),
    #修改业务
    (r"/api/config/modify_content", modify_content),

    #查询等级列表
     (r"/api/config/query_level", query_level),
    # 修改密码
    (r"/api/config/modify_pwd", modify_pwd),
    # 检测是否登陆
    (r"/api/config/islogin", islogin),
]